import { useRouter } from "next/router";
import { useState } from "react";
import { connect } from "react-redux";
// css
import styles from '@/styles/ShoppingCart.module.scss';
// api
import { commitCartList } from '@/api/cart';

const CartSettle = ({ cart: { checkedNum, checkedPrice, cartList } }) => {
    const router = useRouter();
    const [loading, setLoading] = useState(false);
    // 去结算
    const goSettle = () => {
        const ids = [];
        cartList.forEach(item => {
            const { goodsCartActivityListDTO } = item;
            goodsCartActivityListDTO.forEach(dto => {
                dto.checked && ids.push(dto.id);
            })
        });
        setLoading(true);
        commitCartList({
            ids
        }).then(res => {
            const { code, data } = res;
            if(code == 0){
                const { goodsCartActivityItemDTO } = data || {};
                sessionStorage.setItem('cartList', JSON.stringify(goodsCartActivityItemDTO));
                router.push(`/shopping_cart/order?t=${new Date().getTime()}`);
            }
            setLoading(false);
        })
    }
    return (
        <div className={styles['table-order']}>
            <button disabled={!checkedNum || loading} onClick={goSettle}>去结算</button>
            <span className={styles['price']}><em>￥</em><b>{checkedPrice}</b></span>
            <span className={styles['title']}>总金额</span>
            <span className={styles['amount']}>已选择<em>{checkedNum}</em>件商品，</span>
        </div>
    )
}
const mapStateToProps = state => {
    return {
        cart: state.cart
    }
}
export default connect(mapStateToProps, null)(CartSettle)